package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ASUS
 * Date: 2025-04-28
 * Time: 11:21
 */
/*
通用配置
 */
public class Utils {
    public static WebDriver driver;
    public static  WebDriver createDriver() {
        if (driver == null) {
            // 创建驱动对象
            WebDriverManager.chromedriver().setup();
            ChromeOptions options = new ChromeOptions();
            // 设置无头模式
            options.addArguments("-headless");
            // 设置浏览器加载策略
            options.setPageLoadStrategy(PageLoadStrategy.NORMAL);
            // 允许访问所以链接
            options.addArguments("--remote-allow-origins=*");
            // 驱动创建好了
            driver = new ChromeDriver(options);
            // 创建隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));
        }
        return driver;
    }
    public Utils(String url) {
        // 调用 driver 对象
        driver = createDriver();
        // 访问 url
        driver.get(url);
    }

    /*
    创建屏幕截图
     */
    public void getScreenShot(String str) throws IOException {
        // 屏幕截图
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        // 生成文件的格式为: 年-月-日/test.类名-时分秒毫秒.png
        String fileName = "./src/test/image/" + dirTime + "/" + str + "-" + fileTime + ".png";
        // System.out.printf("fileName:" + fileName);
        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

        // srcFile 放到指定位置
        FileUtils.copyFile(srcFile,new File((fileName)));
    }

}
